import { NestFactory } from '@nestjs/core';
import { VersioningType, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import * as session from 'express-session'; // 引入session
import * as cors from 'cors'; // 引入跨域处理

import { NestExpressApplication } from '@nestjs/platform-express'; // 增加app的类型提示
import { join } from 'path';
import { HttpResponse } from './common/httpResponse';
import { HttpFilter } from './common/httpFilter';

import { RoleGuard } from './guard/role/role.guard';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

const whiteList = ['/list']; // 白名单
function middleWareAll  (req,res,next) {
  console.log(req.originalUrl,'--> 进入全局中间件');
  if(!whiteList.includes(req.originalUrl)){
    next();
  }else{
    res.send({
      code: 200,
      msg: '小黑子露出鸡脚了吧',
    }); // 此处测试用，如果不是list则提示小黑子
  }
}

async function bootstrap() {
  const app:any = await NestFactory.create<NestExpressApplication>(AppModule);
  const options = new DocumentBuilder().addBearerAuth().setTitle('nest').setDescription('nest测试项目').setVersion('1.0').build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/api-docs', app, document); // http://localhost:3000/api-docs

  // 开启版本控制
  app.enableVersioning({
    type: VersioningType.URI
  });

  // 注入session
  app.use(session({ 
    secret: "yuhao", 
    rolling: true,
    name: "yuhao.sid",
    cookie: { maxAge: 300000 }, // cookie过期时间
  })); 

  // 跨域处理-放在上方
  app.use(cors());

  // 全局 中间件
  app.use(middleWareAll);

  // 文件静态资源目录
  app.useStaticAssets(join(__dirname,'images'),{
    prefix:"/img", // http://localhost:3000/img/1679279164306.jpg
  });

  app.useGlobalInterceptors(new HttpResponse()); // 全局响应拦截器
  app.useGlobalFilters(new HttpFilter()); // 全局异常拦截器
  app.useGlobalPipes(new ValidationPipe()); // 全局验证pipe
  app.useGlobalGuards(new RoleGuard()); // 全局守卫

  await app.listen(3000);
}
bootstrap();
